﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _80递归遍历文件夹中的文件
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Walk(@"C:\", p =>
            {
                if (p.EndsWith(".txt"))
                {
                    Console.WriteLine(p);
                }
            }, null);
        }

        private static void Walk(string dir, Action<string> fileAction, Action<string> dirAction)
        {
            try
            {
                //输出这个文件夹中的所有文件
                string[] files = Directory.GetFiles(dir);
                for (int i = 0; i < files.Length; i++)
                {
                    //  Console.WriteLine(files[i]);
                    fileAction?.Invoke(files[i]);
                }

                //对子文件夹执行相同的操作
                string[] subDirs = Directory.GetDirectories(dir);
                for (int i = 0; i < subDirs.Length; i++)
                {
                    dirAction?.Invoke(subDirs[i]);
                    Walk(subDirs[i], fileAction, dirAction);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("拒绝访问:" + e.Message);
            }
        }
    }
}